"use strict";
const db = uniCloud.database();
const fs = require('fs');
const path = require('path');

function readJsonSafe(fullPath) {
  try {
    return JSON.parse(fs.readFileSync(fullPath, 'utf8'));
  } catch (e) { return null; }
}

function resolveDatabasePath(file) {
  return path.join(__dirname, '..', '..', 'database', file);
}

function resolveSeedPath(file) {
  return path.join(__dirname, 'seed', file);
}

function loadSeedJson(file) {
  return readJsonSafe(resolveSeedPath(file));
}

exports.main = async (event, context) => {
  const force = !!(event && event.force);
  const results = { app_config: null, mbti_low: null, mbti_medium: null, mbti_high: null, tarot: null };

  // 预加载 database 下的数据（若存在）
  const dbAppConfig = readJsonSafe(resolveDatabasePath('app_config.json'));
  const dbMbtiAgg = readJsonSafe(resolveDatabasePath('mbti_questions.json')); // {low, medium, high}
  const dbTarot = readJsonSafe(resolveDatabasePath('tarot_cards.json'));

  // app_config（优先 database，再默认值）
  try {
    const col = db.collection('app_config');
    const existed = await (async () => {
      try { const { data } = await col.limit(1).get(); return Array.isArray(data) && data.length > 0; } catch(e) { return false; }
    })();
    if (existed && force) {
      try { await col.where({}).remove(); } catch (e) {}
    }
    const existedAfter = await (async () => {
      try { const { data } = await col.limit(1).get(); return Array.isArray(data) && data.length > 0; } catch(e) { return false; }
    })();
    if (!existedAfter) {
      const appConfig = dbAppConfig || {
        configVersion: 2,
        mbti: { low: 1, medium: 1, high: 1 },
        mbtiTarget: { low: 16, medium: 48, high: 96 },
        tarot: { major: 1 },
        spreads: {
          single: { positions: [{ index: 0, label: '整体' }] },
          three: { positions: [ { index: 0, label: '过去' }, { index: 1, label: '现在' }, { index: 2, label: '未来' } ] }
        }
      };
      const r = await col.add(appConfig);
      results.app_config = { insertedId: r.id || r.insertedId };
    } else {
      results.app_config = { skipped: true, reason: 'collection not empty' };
    }
  } catch (e) {}

  // MBTI 三档（优先 database/mbti_questions.json 聚合 -> seed 单文件 -> 跳过）
  const mbtiCol = db.collection('mbti_questions');
  if (force) {
    try { await mbtiCol.where({}).remove(); } catch (e) {}
  }
  for (const level of ['low','medium','high']) {
    try {
      const { data } = await mbtiCol.where({ level }).limit(1).get();
      const existed = Array.isArray(data) && data.length > 0;
      if (!existed) {
        let payload = null;
        if (dbMbtiAgg && dbMbtiAgg[level]) {
          payload = dbMbtiAgg[level]; // {version, questions}
        }
        if (!payload) {
          const mapFile = { low: 'mbti_low.json', medium: 'mbti_medium.json', high: 'mbti_high.json' };
          payload = loadSeedJson(mapFile[level]);
        }
        if (payload) {
          const doc = { level, version: payload.version || 1, questions: payload.questions || [] };
          const r = await mbtiCol.add(doc);
          results['mbti_' + level] = { insertedId: r.id || r.insertedId, count: doc.questions.length };
        } else {
          results['mbti_' + level] = { skipped: true, reason: 'no payload found' };
        }
      } else {
        results['mbti_' + level] = { skipped: true, reason: 'level exists' };
      }
    } catch (e) {
      results['mbti_' + level] = { error: true };
    }
  }

  // 塔罗（优先 database/tarot_cards.json -> seed/tarot_major.json -> 跳过）
  try {
    const col = db.collection('tarot_cards');
    if (force) {
      try { await col.where({}).remove(); } catch (e) {}
    }
    const existed = await (async () => {
      try { const { data } = await col.limit(1).get(); return Array.isArray(data) && data.length > 0; } catch(e) { return false; }
    })();
    if (!existed) {
      let payload = dbTarot;
      if (!payload) {
        payload = loadSeedJson('tarot_major.json');
      }
      if (payload) {
        const doc = { version: payload.version || 1, cards: payload.cards || [] };
        const r = await col.add(doc);
        results.tarot = { insertedId: r.id || r.insertedId, count: doc.cards.length };
      } else {
        results.tarot = { skipped: true, reason: 'no payload found' };
      }
    } else {
      results.tarot = { skipped: true, reason: 'collection not empty' };
    }
  } catch (e) {}

  return { code: 0, data: results };
}; 